package com.thread;

public class DeadLock implements Runnable{
	private Object obj1 = new Object();
	private Object obj2 = new Object();
	private Boolean flag = true;
	
	public Boolean getFlag() {
		return flag;
	}

	public void setFlag(Boolean flag) {
		this.flag = flag;
	}

	@Override
	public void run() {
		if(flag) {
			synchronized (obj1) {
				while(true) {
					System.out.println("true... obj1");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
					synchronized (obj2) {
						System.out.println("true... obj2");
					}
				}
			}
		}else {
			synchronized (obj2) {
				while(true) {
					System.out.println("false... obj2");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
					synchronized (obj1) {
						System.out.println("false... obj1");
					}
				}
			}
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		DeadLock l = new DeadLock();
		l.setFlag(true);
		Thread t1 = new Thread(l);
		t1.start();
		Thread.sleep(100); //这里需要等待一些时间， 否则不会走true的if。
		l.setFlag(false);
		Thread t2 = new Thread(l);
		t2.start();
	}
}
